<template>
  <el-dialog
    width="60%"
    top="70px"
    :visible.sync="visible"
    :title="dataForm.details ? '详情' : !dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="close()"
    :destroy-on-close="true"
    @opened="opened()"
  >
    <el-form
      class="dialogInner"
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      :label-width="$i18n.locale === 'en-US' ? '140px' : '130px'"
      :disabled="disabled"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="套餐类型" prop="comboType">
            <el-select v-model="dataForm.comboType" placeholder="请选择">
              <el-option
                v-for="item in optionslaixing"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="套餐名称" prop="comboName">
            <el-input v-model="dataForm.comboName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格" prop="price">
            <el-input v-model="dataForm.price"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="说明" prop="comboExplain">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="dataForm.comboExplain"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60">
            <span style="color: #f56c6c; margin-right: 4px">*</span>封面图<span
              >(支持png、jpg，最多1张)</span
            >
          </p>
        </el-col>
        <el-col :span="24">
          <el-form-item label="" prop="cover">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :on-success="(res, file) => handleAvatarSuccess(res, 'cover')"
              :before-upload="(file) => beforeUploadHandle(file, 'cover')"
            >
              <img v-if="dataForm.cover" :src="dataForm.cover" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <p class="pdl60">
            <span style="color: #f56c6c; margin-right: 4px">*</span
            >套餐图片<span>(支持png、jpg，最多10张)</span>
          </p>
        </el-col>
        <el-col :span="24">
          <el-form-item label="" prop="introduction">
            <el-upload
              :preview-src-list="dataForm.introduction"
              :action="url"
              :file-list="fileListtwo"
              :limit="10"
              :before-upload="
                (file) => beforeUploadHandle(file, 'introduction')
              "
              list-type="picture-card"
              :on-success="successHandletwo"
              :on-remove="handleRemovetwo"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer" v-if="!disabled">
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{
        $t("confirm")
      }}</el-button>
    </template>
    <!-- 裁剪框 -->
    <cropper-dlg
      v-if="showCropper"
      :dialogVisible.sync="showCropper"
      :img-file="currentFile"
      ref="vueCropper"
      @upload="cropperUpload"
    ></cropper-dlg>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import debounce from "lodash/debounce";
import mixinRegionModule from "@/mixins/region-module";

export default {
  mixins: [mixinRegionModule],

  data() {
    return {
      optionslaixing: [
        {
          value: 1,
          label: "包桌",
        },
        {
          value: 2,
          label: "按人均",
        },
      ],
      fileList: [],
      fileListtwo: [],
      activeName: "first",
      visible: false,
      startTime: "",
      endTime: "",
      scenicOptions: [],
      url: `${
        window.SITE_CONFIG["apiURL"]
      }/oss/file/aliyunUpload?access_token=${Cookies.get("access_token")}`,
      num: 0,
      dataForm: {
        homestayId: this.$store.state.user.homestayId,
        comboType: "",
        comboName: "",
        price: "",
        comboExplain: "",
        cover: "",
        introduction: "",
      },
      mapPos: [],
      currentFile: "",
      cropperIndex: null,
      showCropper: false, //裁剪弹框
      isCropper: true, //上传之前是否显示裁剪
    };
  },
  props: {
    disabled: Boolean,
  },

  computed: {
    dataRule() {
      return {
        comboType: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        comboName: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        comboExplain: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        price: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        cover: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
        introduction: [
          {
            required: true,
            message: this.$t("validate.required"),
            trigger: "change",
          },
        ],
      };
    },
  },
  components: {},
  methods: {
    handleAvatarSuccess(res, file, key) {
      this.dataForm[key] = res.data.url;
    },
    handleRemovetwo(file, fileList) {
      if (fileList.length == 0) {
        this.dataForm.introduction = "";
      } else {
        this.dataForm.introduction = fileList
          .map((item) => {
            return item;
          })
          .toString();
      }
    },
    successHandletwo(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.fileListtwo.unshift({
        name: "",
        url: res.data.url,
      });
      this.dataForm.introduction = this.fileListtwo
        .map((item) => {
          return item.url;
        })
        .toString();
    },
    // 上传成功
    successHandle1(res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg);
      }
      this.dataForm.cover = res.data.url;
    },
    // 上传之前
    beforeUploadHandle(file, name) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error(
          this.$t("upload.tip", {
            format: "jpg、png、gif",
          })
        );
        return false;
      }
      if (this.isCropper) {
        //显示裁剪
        this.currentFile = file;
        this.cropperIndex = name;
        this.showCropper = true;
        this.$nextTick(() => {
          this.$refs.vueCropper.init();
        });
        return false;
      }
    },
    cropperUpload(data) {
      this.showCropper = false;
      if (data != "close") {
        //裁剪成功后获取的图片
        this.$http.post("/oss/file/aliyunUpload", data).then((res) => {
          if (res.data.code == 0) {
            // 套餐图
            if (this.cropperIndex == "introduction") {
              this.successHandletwo(res.data);
            } else {
              //封面图
              this.handleAvatarSuccess(res.data, "", this.cropperIndex);
            }
          }
        });
      }
    },

    opened() {
      //  this.dataForm.cover='';
      //  this.dataForm.introduction='';
      // this.fileListtwo=[];
      // this.provincAreaDetailInfoList();
      //  this.getScenicOptions();
      //   if (this.dataForm.city) {
      //       this.cityAreaDetailInfoList(this.dataForm.province);
      //   }
      //   if (this.dataForm.area) {
      //       this.countyAreaDetailInfoList(this.dataForm.city);
      //   }
    },
    close() {
      this.dataForm = {
        comboType: "",
        comboName: "",
        price: "",
        comboExplain: "",
        cover: "",
        introduction: "",
        homestayId: this.$store.state.user.homestayId,
      };
      this.fileListtwo = [];
      this.$emit("changeDisabled");
    },
    init() {
      this.visible = true;

      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.getInfo();
        }
      });
    },
    // 获取信息
    getInfo() {
      this.dataForm.cover = "";
      this.dataForm.introduction = "";
      this.fileListtwo = [];

      this.$http
        .get("/hotel/repast/" + this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          }
          this.dataForm = res.data;
          //     this.dataForm = {
          //     ...this.dataForm,
          //     ...res.data,
          // };
          // console.log('this.dataForm',this.dataForm)
          if (this.dataForm.introduction) {
            let lsdata = this.dataForm.introduction.split(",");
            this.fileListtwo = lsdata.map((item, index, arr) => {
              let json = {};
              json.name = "";
              json.url = item;
              return json;
            });
          } else {
            this.fileListtwo = [];
          }

          // this.fileListtwo=this.dataForm.introduction.split(',');
          //                     console.log('111111111111111111',this.fileListtwo)
        })
        .catch(() => {});
    },
    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs["dataForm"].validate((valid) => {
          if (!valid) {
            return false;
          }

          this.$http[!this.dataForm.id ? "post" : "put"](
            "/hotel/repast/",
            this.dataForm
          )
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg);
              }
              this.$message({
                message: this.$t("prompt.success"),
                type: "success",
                duration: 500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                },
              });
            })
            .catch(() => {});
        });
      },
      1000,
      {
        leading: true,
        trailing: false,
      }
    ),
  },
};
</script>
